package com.pqc.tbk.service.admin.money;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pqc.tbk.dao.money.ConfirmMoneyOutDao;
import com.pqc.tbk.dao.money.MoneyInoutDao;
import com.pqc.tbk.dao.user.UserDao;
import com.pqc.tbk.entity.ConstProp;
import com.pqc.tbk.entity.account.User;
import com.pqc.tbk.entity.money.ConfirmMoneyOut;
import com.pqc.tbk.entity.money.MoneyInout;

/**
 * 
 * @author long, create on 2012-8-2 上午1:00:49
 * 
 */
@Service
@Transactional(readOnly = true)
public class ConfirmMoneyOutServiceImpl implements ConfirmMoneyOutService {

	private ConfirmMoneyOutDao confirmMoneyOutDao;
	private UserDao userDao;
	private MoneyInoutDao moneyInoutDao;

	@Override
	public Page<ConfirmMoneyOut> getPage(final String condition,
			final Pageable pageable) {
		return confirmMoneyOutDao.getSearchPage(condition, pageable,
				ConfirmMoneyOut.class);
	}

	@Override
	public ConfirmMoneyOut findById(final Long id) {
		return confirmMoneyOutDao.findOne(id, ConfirmMoneyOut.class);
	}

	@Override
	@Transactional(readOnly = false)
	public void saveOrUpdate(final ConfirmMoneyOut out) {
		confirmMoneyOutDao.update(out);
		if (out.getState().equals(ConstProp.ConfirmMoneyInout.HAVE_PAY)) {
			// 更改账户余额
			final User user = userDao.findOne(out.getUid(), User.class);
			user.setMoney_rest(user.getMoney_rest() - out.getMoney());
			userDao.update(user);
			// 财务表中插入一条记录
			final MoneyInout moneyInout = new MoneyInout();
			moneyInout.setType(ConstProp.MoneyInout.OUT);
			moneyInout.setUid(out.getUid());
			moneyInout.setMoney(out.getMoney());
			moneyInoutDao.save(moneyInout);
		}
	}

	@Autowired
	public void setConfirmMoneyOutDao(
			final ConfirmMoneyOutDao confirmMoneyOutDao) {
		this.confirmMoneyOutDao = confirmMoneyOutDao;
	}

	@Autowired
	public void setUserDao(final UserDao userDao) {
		this.userDao = userDao;
	}

	@Autowired
	public void setMoneyInoutDao(final MoneyInoutDao moneyInoutDao) {
		this.moneyInoutDao = moneyInoutDao;
	}

}
